const { spawn } = require('child_process');
const fs = require('fs-extra');

let frontendProcess = null;
let backendProcess = null;

function startFrontend() {
  frontendProcess = spawn('npm', ['run', 'dev'], {
    cwd: './frontend',
    stdio: 'inherit',
    shell: true
  });
}

function startBackend() {
  backendProcess = spawn('uvicorn', ['backend.main:app', '--host', '127.0.0.1', '--port', '8001', '--reload'], {
    stdio: 'inherit',
    shell: true,
    env: { ...process.env, PYTHONIOENCODING: 'utf-8' }
  });
}

function stopProcess(proc) {
  if (proc) {
    proc.kill('SIGTERM');
  }
}

function restartAll() {
  console.log('♻️  正在重启前后端服务...');
  stopProcess(frontendProcess);
  stopProcess(backendProcess);
  setTimeout(() => {
    startFrontend();
    startBackend();
  }, 1000); // 稍等1秒，确保端口释放
}

// 启动
console.log('🚀 启动开发环境...');
fs.writeFileSync('backend/.env', 'ENV=development');
startFrontend();
startBackend();

// 捕获信号，重启服务
process.on('SIGINT', () => {
  restartAll();
});
process.on('SIGTERM', () => {
  restartAll();
});